# @Time    : 2024/1/25 21:07
# @Author  : 🍁
# @File    : project.py
# @Software: PyCharm
from django import forms
from django.core.exceptions import ValidationError

from web.models import Project
from web.forms.bootstrap import BootStrap
from web.forms.widgets import ColorWidgets


class ProjectListForm(BootStrap, forms.ModelForm):
    BootStrap_class_exclude = ["color"]

    # description = forms.CharField(label="描述", widget=forms.Textarea(attrs={}))

    class Meta():
        model = Project
        fields = ["project_title", "color", "description"]
        # 可以通过上面的方式修改，也可以用下面的方式
        labels = {
            "description": "描述"
        }
        widgets = {
            "description": forms.Textarea(attrs={}),
            # 自定义组件
            "color": ColorWidgets(attrs={"class": "color-radio"})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_project_title(self):
        # 验证用户是否创建过该项目
        project_title = self.cleaned_data["project_title"]
        exists = Project.objects.filter(project_title=project_title, created_by=self.request.tartec.user).exists()
        if exists:
            raise ValidationError("项目名已存在")

        # 验证用户是否符合创建项目
        # 获取用户可以创建项目的最大数量
        max_count = self.request.tartec.price_classify.create_projects
        # 获取用户已经创建的数量
        count = Project.objects.filter(created_by=self.request.tartec.user).count()
        if count >= max_count:
            raise ValidationError("已超过最大创建数量，请升级套餐")
        # 校验成功
        return project_title
